package com.flyox.game.militarychess.client.minaclient;

import java.net.InetSocketAddress;
import java.security.GeneralSecurityException;

import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.flyox.game.militarychess.message.ChessPackage;
import com.flyox.game.militarychess.util.ssl.SslContextFactory;

public class MinaClient {
	private final IoHandler handler;
	private IoSession session;

	public MinaClient(IoHandler handler) {
		this.handler = handler;
	}

	public boolean isConnected() {
		if (session != null && session.isConnected()) {
			return true;
		} else {
			return false;
		}
	}

	public boolean connect(NioSocketConnector connector, InetSocketAddress address) {
		if (session != null && session.isConnected()) {
			throw new IllegalStateException("Already connected. Disconnect first.");
		}

		DefaultIoFilterChainBuilder chain = connector.getFilterChain();

		// chain.addLast("mdc", new MdcInjectionFilter());
		try {
			SslFilter sslFilter = new SslFilter(SslContextFactory.getInstance(false));
			sslFilter.setUseClientMode(true);
			chain.addLast("sslFilter", sslFilter);
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		}
		chain.addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
		// chain.addLast("logger", new LoggingFilter());
		connector.setHandler(handler);
		ConnectFuture future = connector.connect(address);

		future.awaitUninterruptibly();
		if (!future.isConnected()) {
			return false;
		}
		session = future.getSession();

		// 登录
		// ChessPackage cp=new ChessPackage(CONSTS.CMD_HELLO);
		// session.write(cp);

		return true;
	}

	public void sendRequest(ChessPackage cp) {
		session.write(cp);
	}

	public void close() {
		if (session != null) {
//			if (session.isConnected()) {
//				session.getCloseFuture().awaitUninterruptibly();
//			}
			session.close();
		}
	}
}
